package com.channel.temperature.collect.ui.fragment

import android.content.res.Configuration
import android.graphics.Color
import android.graphics.Typeface
import android.os.Bundle
import android.os.Environment
import android.util.Log
import android.view.View
import android.widget.LinearLayout
import android.widget.SeekBar
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import com.github.mikephil.charting.components.Legend
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.components.YAxis
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.data.LineData
import com.github.mikephil.charting.data.LineDataSet
import com.github.mikephil.charting.highlight.Highlight
import com.github.mikephil.charting.listener.OnChartValueSelectedListener
import com.github.mikephil.charting.utils.ColorTemplate
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.gyf.immersionbar.ktx.immersionBar
import com.hjq.toast.ToastUtils
import com.hjy.bluetooth.HBluetooth
import com.kongzue.dialogx.dialogs.BottomMenu
import com.kongzue.dialogx.dialogs.MessageDialog
import com.kongzue.dialogx.dialogs.WaitDialog
import com.kongzue.dialogx.interfaces.OnDialogButtonClickListener
import com.kongzue.dialogx.interfaces.OnMenuItemClickListener
import com.channel.temperature.collect.R
import com.channel.temperature.collect.app.base.BaseFragment
import com.channel.temperature.collect.app.ext.LiveDataEvent
import com.channel.temperature.collect.app.ext.initBack
import com.channel.temperature.collect.app.ext.mmkv
import com.channel.temperature.collect.app.util.CRC16Utils
import com.channel.temperature.collect.app.util.ExcelUtil
import com.channel.temperature.collect.app.util.MyUtil
import com.channel.temperature.collect.app.widget.MyMarkerView
import com.channel.temperature.collect.data.annotation.ValueKey
import com.channel.temperature.collect.data.response.LineDataBean
import com.channel.temperature.collect.data.response.SystemInfoBean
import com.channel.temperature.collect.databinding.FragmentOnlineBinding
import com.channel.temperature.collect.ui.activity.OfflineCollectActivity
import com.channel.temperature.collect.ui.viewmodel.OnlineCollectModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import me.hgj.mvvmhelper.base.MvvmHelper
import me.hgj.mvvmhelper.base.appContext
import me.hgj.mvvmhelper.ext.setOnclickNoRepeat
import me.hgj.mvvmhelper.ext.toStartActivity
import java.io.File
import java.util.Date

class OnlineCollectFragment : BaseFragment<OnlineCollectModel, FragmentOnlineBinding>(),
    OnChartValueSelectedListener, SeekBar.OnSeekBarChangeListener {
    protected var tfLight: Typeface? = null

    val actionList = mutableListOf<String>(
        "显示/隐藏 板载温度",
        "显示/隐藏 环境温度",
        "显示/隐藏 环境压力",
    )
    val colorIntList = mutableListOf<Int>(
        R.color.color0,
        R.color.color1,
        R.color.color2,
        R.color.color3,
        R.color.color4,
        R.color.color5,
        R.color.color6,
        R.color.color7,
        R.color.color8,
        R.color.color9,
        R.color.color10,
        R.color.color11
    )

    companion object {
        fun newInstance(): OnlineCollectFragment {
            val args = Bundle()
            val fragment = OnlineCollectFragment()
            fragment.arguments = args
            return fragment
        }
    }

    override fun initView(savedInstanceState: Bundle?) {
        mBind.customToolbar.initBack("保压取心工具数据测量") {
            val messageDialog = MessageDialog(
                "提示", "退出程序？", "确定", "取消"
            ).setButtonOrientation(LinearLayout.HORIZONTAL)
            messageDialog.okButtonClickListener = OnDialogButtonClickListener { dialog, v ->
                lifecycleScope.launch {
                    HBluetooth.getInstance().release()
                    activity?.finish()
                }
                false
            }
            if (this.resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE) {
                messageDialog.setMaxWidth(resources.displayMetrics.widthPixels / 2)
            }
            messageDialog.show()
        }
        mBind.customToolbar.setRightDrawable(R.mipmap.icon_select_menu)

        mViewModel.startReadOnlineData.value = false
        mViewModel.continueReadCMD = false
        mViewModel.currentDataString.value = ""
        mViewModel.resetClickType()
        tfLight = Typeface.createFromAsset(
            MvvmHelper.app.applicationContext.assets, "OpenSans-Light.ttf"
        )

        mBind.chart.setOnChartValueSelectedListener(this)

        // create marker to display box when values are selected
        val mv = MyMarkerView(
            MvvmHelper.app.applicationContext, R.layout.custom_marker_view
        )

        // Set the marker to the chart

        // Set the marker to the chart
        mv.setChartView(mBind.chart)
        mBind.chart.setMarker(mv)

        mBind.chart.description.isEnabled = false;
        mBind.chart.setTouchEnabled(true)
        mBind.chart.dragDecelerationFrictionCoef = 0.9f
        mBind.chart.setDragEnabled(true);
        mBind.chart.setScaleEnabled(true);
        mBind.chart.setDrawGridBackground(false);
        mBind.chart.setHighlightPerDragEnabled(true);
        mBind.chart.setPinchZoom(false);
        mBind.chart.setBackgroundColor(appContext.resources.getColor(R.color.colorLine));

        mBind.chart.setNoDataText("")
        mBind.chart.setNoDataTextColor(R.color.common_text_color)


        // get the legend (only possible after setting data)
        // get the legend (only possible after setting data)
        val l: Legend = mBind.chart.getLegend()

        // modify the legend ...

        // modify the legend ...
        l.form = Legend.LegendForm.LINE
        l.typeface = tfLight
        l.textSize = 11f
        l.textColor = requireActivity().resources.getColor(R.color.color_666666)
        l.verticalAlignment = Legend.LegendVerticalAlignment.BOTTOM
        l.horizontalAlignment = Legend.LegendHorizontalAlignment.LEFT
        l.orientation = Legend.LegendOrientation.HORIZONTAL
        l.setDrawInside(false)
//        l.setYOffset(11f);

        //        l.setYOffset(11f);
        val xAxis: XAxis = mBind.chart.getXAxis()
        xAxis.typeface = tfLight
        xAxis.textSize = 11f
        xAxis.textColor = ColorTemplate.getHoloBlue()
        xAxis.setDrawGridLines(false)
        xAxis.setDrawAxisLine(false)

        val leftAxis: YAxis = mBind.chart.getAxisLeft()
        leftAxis.typeface = tfLight
        leftAxis.textColor = ColorTemplate.getHoloBlue()
        leftAxis.axisMaximum = mViewModel.leftMaxValue
        leftAxis.axisMinimum = mViewModel.leftMinValue
        leftAxis.setDrawZeroLine(false)
        leftAxis.setDrawGridLines(false)
        leftAxis.isGranularityEnabled = false

        val rightAxis: YAxis = mBind.chart.getAxisRight()
        rightAxis.typeface = tfLight
        rightAxis.textColor = Color.RED
        rightAxis.axisMaximum = mViewModel.rightMaxValue
        rightAxis.axisMinimum = mViewModel.rightMinValue
        rightAxis.setDrawGridLines(false)
        rightAxis.setDrawZeroLine(false)
        rightAxis.isGranularityEnabled = false

        mBind.seekBar1.setOnSeekBarChangeListener(this)
        mBind.seekBar2.setOnSeekBarChangeListener(this)
        mBind.seekBar3.setOnSeekBarChangeListener(this)
        mBind.seekBar4.setOnSeekBarChangeListener(this)

        mBind.leftMaxET.setText("" + mBind.seekBar1.progress)
        mBind.leftMinET.setText("" + mBind.seekBar2.progress)
        mBind.rightMaxET.setText("" + mBind.seekBar3.progress)
        mBind.rightMinET.setText("" + mBind.seekBar4.progress)

        mBind.seekBar1.progress =
            mmkv.getInt(ValueKey.SEEK_BAR_KEY_1, mViewModel.leftMaxValue.toInt())
        mBind.seekBar2.progress =
            mmkv.getInt(ValueKey.SEEK_BAR_KEY_2, mViewModel.leftMinValue.toInt())
        mBind.seekBar3.progress =
            mmkv.getInt(ValueKey.SEEK_BAR_KEY_3, mViewModel.rightMaxValue.toInt())
        mBind.seekBar4.progress =
            mmkv.getInt(ValueKey.SEEK_BAR_KEY_4, mViewModel.rightMinValue.toInt())
    }

    private fun initListener() {
        HBluetooth.getInstance().setReceiver { dataInputStream, result -> //设备发过来的数据将在这里出现
            mViewModel.handleBLEResult(result)
        }
    }


    /**
     * 懒加载 第一次获取视图的时候 触发
     */
    override fun lazyLoadData() {
    }


    override fun onRequestSuccess() {
        LiveDataEvent.showTitle.observe(this, Observer {
            if (it) {
                lifecycleScope.launch {
                    mBind.titleTv.visibility = View.VISIBLE
                    mBind.titleTv.text = "当前设备：" + mmkv.getString(
                        ValueKey.CURRENT_DEVICE_NAME, ""
                    ).toString()
                }

            }
        })
        mViewModel.startReadOnlineData.observe(this, Observer {

            if (it) {
                if (mViewModel.continueReadCMD == true) {
                    if (mBind.queryTasksTV.text.toString() == "查询在线数据") {
                        mViewModel.isClearDataAction = false
                        mBind.queryTasksTV.text = "查询中"
                        lifecycleScope.launch {
                            HBluetooth.getInstance().sender()?.let { it1 ->
                                var systemInfoString = mmkv.getString(ValueKey.SYSTEM_INFO, "")
                                if (!systemInfoString.isNullOrEmpty()) {
                                    var mInfoBean = Gson().fromJson<Any>(
                                        systemInfoString,
                                        object : TypeToken<SystemInfoBean>() {}.type
                                    ) as SystemInfoBean
                                    var readInterval: Int = (mInfoBean.onlineWorkInterval) * 1000
                                    mViewModel.continueReadCMD = true
                                    flow<Int> {
                                        while (mViewModel.continueReadCMD && HBluetooth.getInstance().isConnected) {
                                            emit(0)
                                            delay(readInterval.toLong())
                                        }
                                    }.collect {
                                        HBluetooth.getInstance().sender()?.let { it1 ->
                                            mViewModel.clickType = 12
                                            var cmd = "FF55AA0003" + getAddress() + "46"
                                            mViewModel.sendCommonCMD(
                                                it1, cmd + CRC16Utils.checkCRC(
                                                    MyUtil.hex2Bytes(
                                                        cmd
                                                    )
                                                )
                                            )
                                        }
                                    }
                                } else {
                                    ToastUtils.show("请先读取系统配置参数")
                                }

                            }
                        }
                    } else {
                        ToastUtils.show("操作中，请勿多次点击")
                    }
                }

            } else {

            }

        })

        mViewModel.mLiveLineData.observe(this, Observer {


            mBind.chart.getAxisLeft().axisMaximum = mBind.seekBar1.progress.toFloat()
            mBind.chart.getAxisRight().axisMaximum = mBind.seekBar3.progress.toFloat()
            mBind.chart.getAxisLeft().axisMinimum = mBind.seekBar2.progress.toFloat()
            mBind.chart.getAxisRight().axisMinimum = mBind.seekBar4.progress.toFloat()

            mBind.noDataIv.visibility = View.GONE
            mBind.tipsLayout.visibility = View.VISIBLE
            if (mViewModel.isClearDataAction) {
                setDataNew(it, true)
            } else {
                setDataNew(it, false)
            }

            mBind.chart.invalidate()
        })
        mViewModel.currentDataString.observe(this, Observer {
            lifecycleScope.launch {
                if (!it.isNullOrEmpty()) {
                    mBind.CurrentDataTv.setTextColor(
                        resources.getColor(
                            colorIntList[mmkv.getInt(
                                ValueKey.COLOR1, 0
                            )]
                        )
                    )
                    mBind.CurrentData1Tv.setTextColor(
                        resources.getColor(
                            colorIntList[mmkv.getInt(
                                ValueKey.COLOR2, 2
                            )]
                        )
                    )
                    mBind.CurrentData2Tv.setTextColor(
                        resources.getColor(
                            colorIntList[mmkv.getInt(
                                ValueKey.COLOR3, 8
                            )]
                        )
                    )
                    mBind.CurrentDataLayout.visibility = View.VISIBLE
                    mBind.CurrentDataTv.text =
                        mViewModel.currentDataString.value?.split(",")?.get(0)
                    mBind.CurrentData1Tv.text =
                        mViewModel.currentDataString.value?.split(",")?.get(1)
                    mBind.CurrentData2Tv.text =
                        mViewModel.currentDataString.value?.split(",")?.get(2)
                } else {
                    mBind.CurrentDataLayout.visibility = View.GONE
                    mBind.CurrentDataTv.text = ""
                    mBind.CurrentData1Tv.text = ""
                    mBind.CurrentData2Tv.text = ""
                }
            }
        })
    }

    override fun onBindViewClick() {
        //绑定点击事件
        setOnclickNoRepeat(
            mBind.customToolbar.getRightId(),
            mBind.queryTasks,
            mBind.stopQuery,
            mBind.clearAll,
            mBind.queryOfflineData,
            mBind.toExcel,
            mBind.setChartLayout,
            mBind.setNormalLayout,
            mBind.toLayout3,
            mBind.toLayout2,
            mBind.confirmAndToLayout2
        ) {
            when (it) {
                mBind.customToolbar.getRightId() -> {
                    BottomMenu.show(actionList as List<CharSequence>?)
                        .setMessage("操作提示").onMenuItemClickListener =
                        OnMenuItemClickListener { dialog, text, index ->
                            if (mBind.chart.getData() != null && mBind.chart.getData()
                                    .getDataSetCount() > 0
                            ) {
                                if (mBind.chart.lineData.getDataSetByIndex(index)?.isVisible == false) {
                                    mBind.chart.lineData.getDataSetByIndex(index)?.isVisible = true
                                } else {
                                    mBind.chart.lineData.getDataSetByIndex(index)?.isVisible = false
                                }

                                mBind.chart.invalidate()
                            } else {
                                ToastUtils.show("请在查看在线数据时操作")
                            }
                            false
                        }

                }

                mBind.toLayout3 -> {
                    mBind.layout1.visibility = View.GONE
                    mBind.layout2.visibility = View.GONE
                    mBind.layout3.visibility = View.VISIBLE
                }

                mBind.toLayout2 -> {
                    mBind.layout1.visibility = View.GONE
                    mBind.layout2.visibility = View.VISIBLE
                    mBind.layout3.visibility = View.GONE
                }

                mBind.confirmAndToLayout2 -> {
                    mBind.layout1.visibility = View.GONE
                    mBind.layout2.visibility = View.VISIBLE
                    mBind.layout3.visibility = View.GONE
                    var canSave = checkCanSave()
                    if (canSave) {
                        mBind.seekBar1.progress = mBind.leftMaxET.text.toString().toInt()
                        mBind.seekBar2.progress = mBind.leftMinET.text.toString().toInt()
                        mBind.seekBar3.progress = mBind.rightMaxET.text.toString().toInt()
                        mBind.seekBar4.progress = mBind.rightMinET.text.toString().toInt()
                        val leftAxis: YAxis = mBind.chart.getAxisLeft()
                        leftAxis.axisMaximum = mBind.seekBar1.progress.toFloat()
                        leftAxis.axisMinimum = mBind.seekBar2.progress.toFloat()
                        val rightAxis: YAxis = mBind.chart.getAxisRight()
                        rightAxis.axisMaximum = mBind.seekBar3.progress.toFloat()
                        rightAxis.axisMinimum = mBind.seekBar4.progress.toFloat()
                        mBind.chart.notifyDataSetChanged()
                        mBind.chart.invalidate()
                    }
                }

                mBind.setNormalLayout -> {
                    mBind.layout1.visibility = View.VISIBLE
                    mBind.layout2.visibility = View.GONE
                    mBind.layout3.visibility = View.GONE
                }

                mBind.setChartLayout -> {
                    mBind.layout1.visibility = View.GONE
                    mBind.layout2.visibility = View.VISIBLE
                    mBind.layout3.visibility = View.GONE

                }

                mBind.queryTasks -> {
                    lifecycleScope.launch {
                        if (HBluetooth.getInstance().isConnected) {
                            if (HBluetooth.getInstance().isConnected) {
                                HBluetooth.getInstance().sender()?.let { it1 ->
                                    mViewModel.clickType = 9
                                    var cmd = "FF55AA000A" + getAddress() + "45010000000000C8"
                                    mViewModel.sendCommonCMD(
                                        it1, cmd + CRC16Utils.checkCRC(MyUtil.hex2Bytes(cmd))
                                    )
                                }
                            } else {
                                ToastUtils.show("请先连接设备后再操作")
                            }

                        } else {
                            ToastUtils.show("请先连接设备后再操作")
                        }
                    }
                }

                mBind.toExcel -> {
                    lifecycleScope.launch {


                        if (mViewModel.excelListData.size > 0) {
                            mBind.queryTasksTV.text = "查询在线数据"
                            mViewModel.continueReadCMD = false
                            mViewModel.isClearDataAction = false
                            mViewModel.startReadOnlineData.value = false
                            mViewModel.resetClickType()

                            try {
                                var filePath = Environment.getExternalStorageDirectory()
                                    .toString() + "/tpcollection"
                                WaitDialog.show("导出中，请等待")
                                lifecycleScope.launch(Dispatchers.Main) {
                                    delay(200)
                                    val result = withContext(Dispatchers.IO) {
                                        var resultList = mViewModel.excelListData


                                        var bzMaxBean = resultList.maxBy { it.gX2 }
                                        var bzMax = MyUtil.formatFloat(
                                            bzMaxBean.gX2, 2, 0.00f
                                        )

                                        var bzMaxTime = MyUtil.DateToStr(
                                            Date(
                                                (bzMaxBean.time.split("&").get(0).toLong()) * 1000
                                            )
                                        )

                                        var bzMinBean = resultList.minBy { it.gX2 }
                                        var bzMin = MyUtil.formatFloat(
                                            bzMinBean.gX2, 2, 0.00f
                                        )
                                        var bzMinTime = MyUtil.DateToStr(
                                            Date(
                                                (bzMinBean.time.split("&").get(0).toLong()) * 1000
                                            )
                                        )

                                        var hjMaxBean = resultList.maxBy { it.pT2 }
                                        var hjMax = MyUtil.formatFloat(
                                            hjMaxBean.pT2, 3, 0.000f
                                        )
                                        var hjMaxTime = MyUtil.DateToStr(
                                            Date(
                                                (hjMaxBean.time.split("&").get(0).toLong()) * 1000
                                            )
                                        )

                                        var hjMinBean = resultList.minBy { it.pT2 }
                                        var hjMin = MyUtil.formatFloat(
                                            hjMinBean.pT2, 3, 0.00f
                                        )

                                        var hjMinTime = MyUtil.DateToStr(
                                            Date(
                                                (hjMinBean.time.split("&").get(0).toLong()) * 1000
                                            )
                                        )

                                        var ylMaxBean = resultList.maxBy { it.pressure2 }
                                        var ylMax = MyUtil.formatFloat(
                                            ylMaxBean.pressure2, 3, 0.000f
                                        )
                                        var ylMaxTime = MyUtil.DateToStr(
                                            Date(
                                                (ylMaxBean.time.split("&").get(0).toLong()) * 1000
                                            )
                                        )

                                        var ylMinBean = resultList.minBy { it.pressure2 }
                                        var ylMin = MyUtil.formatFloat(
                                            ylMinBean.pressure2, 3, 0.000f
                                        )
                                        var ylMinTime = MyUtil.DateToStr(
                                            Date(
                                                (ylMinBean.time.split("&").get(0).toLong()) * 1000
                                            )
                                        )


                                        var file = File(filePath)
                                        if (!file.exists()) {
                                            file.mkdirs()
                                        }
                                        var currentTime = MyUtil.DateToStrFormat(Date())
                                        var excelFileName: String = "/${
                                            mmkv.getString(
                                                ValueKey.CURRENT_DEVICE_NAME, ""
                                            )
                                        }_${
                                            mmkv.getString(
                                                ValueKey.CURRENT_TASK_NAME, ""
                                            )
                                        }_$currentTime.csv"
                                        filePath += excelFileName;
                                        Log.e("目录", "目录  " + filePath)
                                        var title = arrayOf(
                                            "时间", "板载温度(℃)", "环境温度(℃)", "环境压力(MPa)"
                                        )

                                        var deviceName =
                                            mmkv.getString(ValueKey.CURRENT_DEVICE_NAME, "")
                                                .toString()
                                        var taskName =
                                            mmkv.getString(ValueKey.CURRENT_TASK_NAME, "")
                                                .toString()
                                        var taskDec =
                                            mmkv.getString(ValueKey.CURRENT_TASK_DEC, "").toString()
                                        var startTime =
                                            mmkv.getString(ValueKey.COLLECTION_START_TIME, "")
                                        var endTime =
                                            mmkv.getString(ValueKey.COLLECTION_END_TIME, "")

                                        ExcelUtil.writeToExcel(
                                            filePath,
                                            title,
                                            "四川川庆石油钻采科技有限公司",
                                            deviceName,
                                            taskName,
                                            taskDec,
                                            startTime,
                                            endTime,
                                            "" + 1,
                                            "" + bzMax,
                                            "" + bzMin,
                                            bzMaxTime,
                                            bzMinTime,
                                            "" + hjMax,
                                            "" + hjMin,
                                            "" + hjMaxTime,
                                            "" + hjMinTime,
                                            "" + ylMax,
                                            "" + ylMin,
                                            "" + ylMaxTime,
                                            "" + ylMinTime, resultList
                                        );

//                                        ExcelUtil.writeObjListToExcel(
//                                            resultList, filePath, appContext
//                                        );
                                    }
                                    if (result) {
                                        WaitDialog.dismiss(100)
                                        ToastUtils.show("导出Excel成功,文件位置:$filePath")
                                    } else {
                                        WaitDialog.dismiss(100)
                                        ToastUtils.show("导出Excel失败")
                                    }

                                }

                            } catch (e: NumberFormatException) {
                                ToastUtils.show("请输入正确的值")
                            }

                        } else {
                            ToastUtils.show("暂无数据")
                        }

                    }

                }

                mBind.stopQuery -> {
                    lifecycleScope.launch {
                        mBind.queryTasksTV.text = "查询在线数据"
                        mViewModel.continueReadCMD = false
                        mViewModel.isClearDataAction = false
                        mViewModel.startReadOnlineData.value = false
                        mViewModel.resetClickType()
                        ToastUtils.show("暂停成功")
                    }

                }

                mBind.queryOfflineData -> {
                    lifecycleScope.launch {
                        if (HBluetooth.getInstance().isConnected) {
                            mBind.queryTasksTV.text = "查询在线数据"
                            mViewModel.isClearDataAction = false
                            mViewModel.continueReadCMD = false
                            mViewModel.resetClickType()
                            toStartActivity(OfflineCollectActivity::class.java)
                        } else {
                            ToastUtils.show("请先连接设备后再操作")
                        }
                    }

                }

                mBind.clearAll -> {
                    lifecycleScope.launch {
                        val messageDialog = MessageDialog.show(
                            "提示", "清空图表数据并停止读取？", "确定", "取消"
                        )
                        messageDialog.maxWidth =
                            if (appContext.resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE)
                                appContext.resources.displayMetrics.widthPixels / 2 else appContext.resources.displayMetrics.widthPixels
                        messageDialog.okButtonClickListener =
                            OnDialogButtonClickListener { dialog, v ->
                                dialog.dismiss()
                                mBind.queryTasksTV.text = "查询在线数据"
                                mViewModel.continueReadCMD = false
                                mViewModel.startReadOnlineData.value = false
                                mViewModel.clearAllData()
                                mViewModel.currentDataString.value = ""
                                mViewModel.resetClickType()
                                true
                            }

                        mViewModel.isClearDataAction = true
                    }


                }
            }
        }
    }


    fun checkCanSave(): Boolean {
        var canSave = true
        try {
            var leftMax = mBind.leftMaxET.text.toString().toInt()
            var leftMin = mBind.leftMinET.text.toString().toInt()
            var rightMax = mBind.rightMaxET.text.toString().toInt()
            var rightMin = mBind.rightMinET.text.toString().toInt()
            canSave =
                leftMax >= mViewModel.leftMinValue && leftMax <= mViewModel.leftMaxValue && leftMin >= mViewModel.leftMinValue && leftMin <= mViewModel.leftMaxValue && rightMax >= mViewModel.rightMinValue && rightMax <= mViewModel.rightMaxValue && rightMin >= mViewModel.rightMinValue && rightMin <= mViewModel.rightMaxValue
            if (!canSave) {
                ToastUtils.show("请输入在正确范围内的数值")
            }
        } catch (e: NumberFormatException) {
            Log.e("解析异常", "解析异常 ")
            ToastUtils.show("请输入在正确格式的参数")
            canSave = false
        }

        return canSave
    }

    private fun getAddress(): String {
        return "FA"
    }

    private fun setDataNew(mLineData: LineDataBean, isClearData: Boolean) {
        var line1Color = resources.getColor(colorIntList[mmkv.getInt(ValueKey.COLOR1, 0)])
        var line2Color = resources.getColor(colorIntList[mmkv.getInt(ValueKey.COLOR2, 2)])
        var line3Color = resources.getColor(colorIntList[mmkv.getInt(ValueKey.COLOR3, 8)])

//        val set1: LineDataSet
        val set2: LineDataSet
//        val set3: LineDataSet
        val set4: LineDataSet
//        val set5: LineDataSet
        val set6: LineDataSet
        if (mBind.chart.getData() != null && mBind.chart.getData().getDataSetCount() > 0) {
//            set1 = mBind.chart.getData().getDataSetByIndex(0) as LineDataSet
            set2 = mBind.chart.getData().getDataSetByIndex(0) as LineDataSet
            set2.color = line1Color
            set2.fillColor = line1Color
//            set3 = mBind.chart.getData().getDataSetByIndex(2) as LineDataSet
            set4 = mBind.chart.getData().getDataSetByIndex(1) as LineDataSet
            set4.color = line2Color
            set4.fillColor = line2Color
//            set5 = mBind.chart.getData().getDataSetByIndex(4) as LineDataSet
            set6 = mBind.chart.getData().getDataSetByIndex(2) as LineDataSet
            set6.color = line3Color
            set6.fillColor = line3Color
//            set1.values = mLineData.values1
            set2.values = mLineData.values2
//            set3.values = mLineData.values3
            set4.values = mLineData.values4
//            set5.values = mLineData.values5
            set6.values = mLineData.values6
            mBind.chart.getData().notifyDataChanged()
            mBind.chart.notifyDataSetChanged()
        } else {

            set2 = LineDataSet(mLineData.values2, "板载温度")
            set2.axisDependency = YAxis.AxisDependency.LEFT
            set2.color = line1Color
            set2.setCircleColor(Color.WHITE)
            set2.lineWidth = 2f
            set2.circleRadius = 3f
            set2.fillAlpha = 65
            set2.fillColor = line1Color
            set2.setDrawCircleHole(false)
            set2.setDrawCircles(false)
            set2.setDrawValues(false)
            set2.highLightColor = Color.rgb(244, 117, 117)


            set4 = LineDataSet(mLineData.values4, "环境温度")
            set4.axisDependency = YAxis.AxisDependency.LEFT
            set4.color = line2Color
            set4.setCircleColor(Color.WHITE)
            set4.lineWidth = 2f
            set4.circleRadius = 3f
            set4.fillAlpha = 65
            set4.fillColor = line2Color
            set4.setDrawCircleHole(false)
            set4.setDrawCircles(false)
            set4.setDrawValues(false)
            set4.highLightColor = Color.rgb(244, 117, 117)


            set6 = LineDataSet(mLineData.values6, "环境压力")
            set6.axisDependency = YAxis.AxisDependency.RIGHT
            set6.color = line3Color
            set6.setCircleColor(Color.WHITE)
            set6.lineWidth = 2f
            set6.circleRadius = 3f
            set6.fillAlpha = 65
            set6.fillColor = line3Color
            set6.setDrawCircleHole(false)
            set6.setDrawCircles(false)
            set6.setDrawValues(false)
            set6.highLightColor = Color.rgb(244, 117, 117)

            // create a data object with the data sets
            val data = LineData(set2, set4, set6)
            data.setValueTextColor(Color.WHITE)
            data.setValueTextSize(9f)

            // set data
            mBind.chart.setData(data)
            if (!isClearData) {
                mBind.chart.setVisibleXRangeMaximum(10F)
                mBind.chart.moveViewToX(10F)
            } else {

            }

        }
    }

    override fun onValueSelected(e: Entry?, h: Highlight?) {
        e?.let {
            mBind.chart.centerViewToAnimated(
                it.x, e.y, h?.let { it1 ->
                    mBind.chart.data.getDataSetByIndex(it1.dataSetIndex).axisDependency
                }, 500
            )
        };
    }

    override fun onNothingSelected() {
    }

    override fun onPause() {
        super.onPause()
        mViewModel.continueReadCMD = false
        mViewModel.isClearDataAction = false
        mViewModel.startReadOnlineData.value = false
        mViewModel.resetClickType()
        mBind.queryTasksTV.text = "查询在线数据"
    }

    override fun onResume() {
        super.onResume()
        Log.e("onResume", "在线收集")
        initListener()
        immersionBar {
            titleBar(mBind.customToolbar)
        }
    }

    override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
        when (seekBar?.id) {
            mBind.seekBar1.id -> {
                Log.e("onProgressChanged", "操作最大值 " + progress)
                mmkv.putInt(ValueKey.SEEK_BAR_KEY_1, progress)
                mBind.tv1.text = "温度最大值" + mBind.seekBar1.progress
                mBind.leftMaxET.setText("" + mBind.seekBar1.progress)
                val leftAxis: YAxis = mBind.chart.getAxisLeft()
                leftAxis.axisMaximum = progress.toFloat()
                mBind.chart.notifyDataSetChanged()
                mBind.chart.invalidate()
            }

            mBind.seekBar2.id -> {
                Log.e("onProgressChanged", "操作最小值 " + progress)
                mmkv.putInt(ValueKey.SEEK_BAR_KEY_2, progress)
                mBind.tv2.text = "温度最小值" + mBind.seekBar2.progress
                mBind.leftMinET.setText("" + mBind.seekBar2.progress)
                val leftAxis: YAxis = mBind.chart.getAxisLeft()
                leftAxis.axisMinimum = progress.toFloat()
                mBind.chart.notifyDataSetChanged()
                mBind.chart.invalidate()
            }

            mBind.seekBar3.id -> {
                Log.e("onProgressChanged", "操作右边最大值 " + progress)
                mmkv.putInt(ValueKey.SEEK_BAR_KEY_3, progress)
                mBind.tv3.text = "压力最大值" + mBind.seekBar3.progress
                mBind.rightMaxET.setText("" + mBind.seekBar3.progress)
                val rightAxis: YAxis = mBind.chart.getAxisRight()
                rightAxis.axisMaximum = progress.toFloat()
                mBind.chart.notifyDataSetChanged()
                mBind.chart.invalidate()
            }

            mBind.seekBar4.id -> {
                Log.e("onProgressChanged", "操作右边最小值 " + progress)
                mmkv.putInt(ValueKey.SEEK_BAR_KEY_4, progress)
                mBind.tv4.text = "压力最小值" + mBind.seekBar4.progress
                mBind.rightMinET.setText("" + mBind.seekBar4.progress)
                val rightAxis: YAxis = mBind.chart.getAxisRight()
                rightAxis.axisMinimum = progress.toFloat()
                mBind.chart.notifyDataSetChanged()
                mBind.chart.invalidate()
            }
        }
    }

    override fun onStartTrackingTouch(seekBar: SeekBar?) {
    }

    override fun onStopTrackingTouch(seekBar: SeekBar?) {
    }

    override fun onStop() {
        super.onStop()

    }
}